# -*- coding:utf-8 -*-
# @Time     :2024/3/14 21:25
# @Author   :CHNJX
# @File     :excel_handler.py
# @Desc     :封装excel相关方法

from openpyxl import load_workbook, Workbook

class ExcelHandler:
    def __init__(self, workbook_path):
        self.workbook_path = workbook_path
        self.workbook = None
        self.load_workbook()

    def load_workbook(self):
        """加载或创建Excel工作簿"""
        try:
            self.workbook = load_workbook(self.workbook_path)
        except FileNotFoundError:
            self.workbook = Workbook()

    def copy_template_sheet(self, template_sheet_name, new_sheet_name):
        """复制模板Sheet到新Sheet"""
        if template_sheet_name in self.workbook.sheetnames:
            template_sheet = self.workbook[template_sheet_name]
            new_sheet = self.workbook.copy_worksheet(template_sheet)
            new_sheet.title = new_sheet_name
            self.workbook.save(self.workbook_path)
            return True
        else:
            print(f"Template sheet '{template_sheet_name}' not found.")
            return False

    def write_data_to_sheet(self, sheet_name, data):
        """将数据写入指定的Sheet"""
        if sheet_name not in self.workbook.sheetnames:
            print(f"Sheet '{sheet_name}' not found. Creating a new sheet.")
            self.workbook.create_sheet(sheet_name)
        sheet = self.workbook[sheet_name]
        for row_index, row_data in enumerate(data, start=1):
            for column_index, value in enumerate(row_data, start=1):
                sheet.cell(row=row_index, column=column_index, value=value)
        self.workbook.save(self.workbook_path)

